package com.jz.community.moduleauthorization.register.model;

import android.app.Activity;
import android.content.Context;

import com.jz.community.basecomm.net.retrofit.ApiException;
import com.jz.community.basecomm.net.retrofit.ApiUtils;
import com.jz.community.basecomm.net.retrofit.HttpRxObservable;
import com.jz.community.basecomm.net.retrofit.JsonRequestBodyConverter;
import com.jz.community.basecomm.net.retrofit.RxLoadingWrapper;
import com.jz.community.basecomm.net.rxandroid.OnLoadListener;
import com.jz.community.basecomm.bean.LoginInfo;
import com.jz.community.moduleauthorization.login.task.GetLoginPwdTask;
import com.jz.community.basecomm.task.GetSmsCodeTask;
import com.jz.community.moduleauthorization.register.bean.RegisterInfo;
import com.jz.community.moduleauthorization.register.net.RegisterApi;
import com.trello.rxlifecycle2.components.support.RxFragmentActivity;

import java.util.HashMap;

import io.reactivex.Observable;
import io.reactivex.functions.Consumer;

/**
 * Created by Tony.Fan on 2018/3/20 15:46
 */
public class RegisterModelImpl implements RegisterModel {

    private Context mContext;

    public RegisterModelImpl(Context context) {
        mContext = context;
    }

    @Override
    public void requestLoginInfo(String mobi, String password, String loginType, String params, String deviceId, String registrationId, final OnLoadListener<LoginInfo> onLoadListener) {

        new GetLoginPwdTask((Activity) mContext, o -> {
            if (o == null) {
                return;
            }
            onLoadListener.onSuccess((LoginInfo) o);
        }).execute(mobi, password, loginType, params, deviceId, registrationId);
    }

    @Override
    public void requestGetSmsCode(String mobi, String type, OnLoadListener<LoginInfo> onLoadListener) {
        new GetSmsCodeTask((Activity) mContext,true, o -> {
            if (o == null) {
                return;
            }
            onLoadListener.onSuccess((LoginInfo) o);
        }).execute("2",mobi);
    }

    @Override
    public void requestRegisterInfo(HashMap<String, String> map, OnLoadListener<RegisterInfo> onLoadListener) {
        Observable<RegisterInfo> registerInfoObserver = HttpRxObservable.getObservable((RxFragmentActivity) mContext, ApiUtils.getApi(mContext, RegisterApi.class)
                .getRegisterInfo(new JsonRequestBodyConverter<HashMap<String, String>>().convert(map)));
        new RxLoadingWrapper<RegisterInfo>(mContext,false)
                .execute(registerInfoObserver)
                .subscribe(registerInfo -> {
                    onLoadListener.onSuccess(registerInfo);
                }, new Consumer<Throwable>() {
                    @Override
                    public void accept(Throwable throwable) throws Exception {
                        onLoadListener.onFail(ApiException.handleException(throwable).message, ApiException.handleException(throwable).code);
                    }
                });
    }
}
